import os
import time
from datetime import datetime, timedelta
import logging
from logging.handlers import RotatingFileHandler

# 配置日志
LOG_DIR = 'logs'
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

logger = logging.getLogger('cleanup_logger')
logger.setLevel(logging.INFO)
log_handler = RotatingFileHandler(
    os.path.join(LOG_DIR, 'cleanup.log'),
    maxBytes=1*1024*1024,  # 1MB
    backupCount=5,
    encoding='utf-8'
)
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)

# 要清理的目录
DATA_DIR = 'data'
# 过期天数
DAYS_TO_KEEP = 2

def delete_old_files(directory, days=DAYS_TO_KEEP):
    """删除指定目录中超过指定天数的文件"""
    if not os.path.exists(directory):
        logger.error(f'目录不存在: {directory}')
        return

    # 计算截止时间
    cutoff_time = datetime.now() - timedelta(days=days)
    logger.info(f'开始清理 {directory} 中超过 {days} 天的文件 (截止时间: {cutoff_time})')

    deleted_count = 0
    skipped_count = 0

    # 遍历目录中的所有文件
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)

        # 确保是文件而不是子目录
        if os.path.isfile(file_path):
            # 获取文件的修改时间
            file_modified_time = datetime.fromtimestamp(os.path.getmtime(file_path))

            # 检查文件是否过期
            if file_modified_time < cutoff_time:
                try:
                    os.remove(file_path)
                    logger.info(f'已删除: {file_path} (修改时间: {file_modified_time})')
                    deleted_count += 1
                except Exception as e:
                    logger.error(f'删除失败: {file_path} - {str(e)}')
                    skipped_count += 1
            else:
                logger.debug(f'未过期: {file_path} (修改时间: {file_modified_time})')
        else:
            logger.debug(f'跳过子目录: {file_path}')
            skipped_count += 1

    logger.info(f'清理完成: 已删除 {deleted_count} 个文件, 跳过 {skipped_count} 个项目')

if __name__ == '__main__':
    delete_old_files(DATA_DIR)